// 统一编辑器接口，当前实现为Monaco
import * as monaco from 'monaco-editor';

let editor: monaco.editor.IStandaloneCodeEditor;

export function initEditor(container: HTMLElement, initialValue: string, onChange: (content: string) => void) {
  editor = monaco.editor.create(container, {
    value: initialValue,
    language: 'sql',
    theme: 'vs',
    fontSize: 18,
    minimap: { enabled: false },
    automaticLayout: true,
    wordWrap: 'on',
    lineNumbers: 'off',
    scrollBeyondLastLine: false,
    roundedSelection: false,
    scrollbar: { vertical: 'hidden', horizontal: 'auto' },
    overviewRulerLanes: 0,
    overviewRulerBorder: false,
    lineDecorationsWidth: 0,
    lineNumbersMinChars: 2
  });
  monaco.languages.register({ id: 'sql' });
  monaco.languages.setMonarchTokensProvider('sql', {
    tokenizer: {
      root: [
        [/\b(load|as|file|data1|skip)\b/i, 'custom-keyword'],
        [/\b(SELECT|FROM|WHERE|INSERT|INTO|VALUES|UPDATE|SET|DELETE|CREATE|TABLE|DROP|ALTER|ADD|AND|OR|NOT|NULL|IS|IN|LIKE|BETWEEN|JOIN|ON|GROUP|BY|ORDER|HAVING|DISTINCT|UNION|ALL|CASE|WHEN|THEN|ELSE|END|LIMIT|OFFSET|ASC|DESC)\b/i, 'keyword'],
        [/--.*/, 'comment'],
        [/\d+/, 'number'],
        [/\'.*?\'/, 'string'],
        [/\".*?\"/, 'string']
      ]
    }
  });
  monaco.editor.defineTheme('custom-sql-theme', {
    base: 'vs',
    inherit: true,
    rules: [
      { token: 'custom-keyword', foreground: 'C71585', fontStyle: 'bold' },
      { token: 'keyword', foreground: '0070C1', fontStyle: 'bold' },
      { token: 'number', foreground: '098658' },
      { token: 'string', foreground: 'A31515' },
      { token: 'comment', foreground: '6A9955', fontStyle: 'italic' }
    ],
    colors: {}
  });
  monaco.editor.setTheme('custom-sql-theme');
  editor.onDidChangeModelContent(() => {
    onChange(editor.getValue());
  });
}

export function getValue() {
  return editor.getValue();
}

export function setValue(val: string) {
  editor.setValue(val);
}

export function setCursorTo(line: number, column: number) {
  editor.setPosition({ lineNumber: line, column });
  editor.focus();
}

export function getLineCount() {
  return editor.getModel()!.getLineCount();
}

export function getLineLength(line: number) {
  return editor.getModel()!.getLineContent(line).length;
} 